library(tidyverse)
library(PlackettLuce)
library(writexl)
library(partykit)

set.seed(20250416)

dataLong = read_delim("rankings.txt")

modelFits = dataLong %>% 
  mutate(sex = factor(sex),
         education = factor(education)) %>% 
  group_by(question) %>% 
  nest %>% 
  mutate(wide = map(data,
                    pivot_wider,
                    id_cols = c(respondent, sex, age, education),
                    names_from = answer,
                    values_from = rank),
         covariates = map(wide,
                          select,
                          sex,
                          age,
                          education),
         group = map(wide,
                     pluck,
                     "respondent"),
         ranking = map(data,
                       ~ rankings(.x,
                                  id = "respondent",
                                  item = "answer",
                                  rank = "rank")),
         ranking = map2(ranking,
                        group,
                        ~ group(.x, .y)),
         model = map2(ranking,
                      covariates,
                      ~ pltree(.x ~ ., 
                               data = .y)))


modelSummary = modelFits %>% 
  mutate(summary = map(model,
                       ~ .x$node$info$test),
         summary = map(summary,
                       as_tibble,
                       rownames = "variable")) %>% 
  select(summary) %>% 
  unnest(summary) %>% 
  pivot_longer(c(sex, age, education)) %>% 
  pivot_wider(id_cols = c(question, name),
              names_from = variable,
              values_from = value)

modelSummary %>% 
  mutate_if(is.numeric, signif, 3) %>% 
  write_xlsx("ranking-covariates.xlsx")
